import axios, { AxiosRequestConfig } from "axios";
import { notification } from "ant-design-vue";
import { axiosConfig } from "@/config";

interface ResponseDataType {
    code: number;
    msg: string;
}

const handleCode = (data: ResponseDataType) => {
    if (data.msg === undefined) {
        notification["error"]({
            message: "系统错误",
        });
    } else {
        notification["error"]({
            message: data.msg,
        });
    }
};

const instance = axios.create({
    baseURL: axiosConfig.baseURL,
    timeout: axiosConfig.timeout,
    headers: {
        "Content-Type": axiosConfig.contentType,
    },
});

instance.interceptors.response.use(
    (response) => {
        const { code } = response.data;
        if (code === 200) {
            return response.data;
        } else {
            handleCode(response.data);
            return Promise.reject(response.data);
        }
    },
    (error) => {
        console.log('error', error);
    }
);

export const post = (options: AxiosRequestConfig) => {
    return instance({ method: "post", ...options });
};

export const get = (options: AxiosRequestConfig) => {
    return instance({ method: "get", ...options });
};

export const put = (options: AxiosRequestConfig) => {
    return instance({ method: "put", ...options });
};

export const remove = (options: AxiosRequestConfig) => {
    return instance({ method: "delete", ...options });
};